<template>
  <div
    v-if="dialogTableVisible1"
    :fullscreen="false"
    :modal="false"
    :show-close="false"
    :width="screenWidth + 20 + 'px'"
    :append-to-body="true"
    style="
      position: absolute;
      left: 6rem;
      margin-top: 42px;
      z-index: 10;
      background-color: white;
    "
    :close-on-click-modal="false"
  >
    <div :style="{ width: screenWidth - 96 + 'px' }">
      <div
        :style="{
          height: '40px',
          borderBottom: '1px solid #ccc',
          width: '100%',
        }"
      >
        <div style="position: absolute; right: 15px">
          <el-button @click="flushed" type="primary"> 刷新</el-button>
          <!-- <el-button v-if="Permission" @click="upButton" type="primary">
        修改业务员</el-button
      > -->
          <!-- <el-button @click="addRow" type="primary">增行</el-button> -->
          <!-- <el-button @click="deleteSelectedRows" type="danger">删除</el-button> -->
          <el-button
            type="primary"
            @click="getAllData(ruleFormRef)"
            v-if="!showInsertButton"
            >保存</el-button
          >
          <!-- <el-button
            type="primary"
            @click="updateMaterialsFixed(ruleFormRef)"
            v-if="!showInsertButton"
            >保存</el-button
          > -->

          <el-button @click="OFFdialogTableVisible" type="danger">关闭</el-button>
        </div>
      </div>
    </div>

    <div
      ref="titleDiv"
      :style="{
        backgroundColor: 'rgba(247, 247, 247, 0.903)',
        height: 120 + 'px',
        width: screenWidth - 96 + 'px',
      }"
    >
      <el-form :model="formMainTable" :inline="true">
        <el-form-item class="labs" style="margin-right: 0">
          <label class="lab" style="width: 100px; padding-right: 5px"
            ><span style="color: red; font-weight: 700">*</span> 工单编码</label
          >
          <el-input
            style="width: 180px"
            v-model="formMainTable.code"
            disabled
            placeholder="自动添加"
          />
        </el-form-item>
        <el-form-item class="labs" style="margin-right: 0">
          <label class="lab" style="width: 100px; padding-right: 5px"> 返修方式 </label>
          <el-select
            v-model="formMainTable.repairMode"
            style="width: 180px"
            @change="handleValueRangeChange()"
          >
            <el-option label="自修" value="0"></el-option>
            <el-option label="委外" value="1"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item class="labs" style="margin-right: 0" v-if="isTotalAmount">
          <label class="lab" style="width: 100px; padding-right: 5px"
            ><span style="color: red; font-weight: 700">*</span> 总金额</label
          >
          <el-input style="width: 180px" v-model="formMainTable.totalAmount" />
        </el-form-item>
        <el-form :model="formMainTable" :inline="true">
          <el-form-item class="labs" style="margin-right: 0">
            <label class="lab" style="width: 100px; padding-right: 5px"
              ><span style="color: red; font-weight: 700">*</span> 周期</label
            >
            <el-input style="width: 180px" v-model="formMainTable.repairTime" clearable />
          </el-form-item>
          <el-form-item class="labs" style="margin-right: 0">
            <label class="lab" style="width: 100px; padding-right: 5px"> 单位 </label>
            <el-select v-model="formMainTable.repairTimeUnit" style="width: 180px">
              <el-option label="小时" value="小时"></el-option>
              <el-option label="天" value="天"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item class="labs" style="margin-right: 0" v-if="isRepairApplication">
            <label class="lab" style="width: 100px; padding-right: 5px"
              ><span style="color: red; font-weight: 700">*</span> 供应商</label
            >
            <el-input style="width: 180px" v-model="formMainTable.supplier" clearable />
          </el-form-item>
          <el-form-item class="labs" style="margin-right: 0" v-if="isRepairApplication">
            <label class="lab" style="width: 100px; padding-right: 5px"
              ><span style="color: red; font-weight: 700">*</span> 供应商地址</label
            >
            <el-input
              style="width: 180px"
              v-model="formMainTable.supplierAddress"
              clearable
            />
          </el-form-item>
        </el-form>
        <el-form :model="form" class="demo-form-inline" :inline="true">
          <el-form-item class="labs" style="margin-right: 0">
            <label class="lab" style="width: 100px; padding-right: 5px">说明</label>
            <el-input style="width: 750px" v-model="formMainTable.explain" clearable />
          </el-form-item>
        </el-form>
      </el-form>
    </div>

    <el-table
      ref="multipleTableRef"
      :data="tableData1"
      stripe
      border
      :row-style="{ height: '20px' }"
      :height="childTableHeight + 'px'"
      style="width: 100%"
      :max-height="childTableHeight + 'px'"
      :cell-style="cellStyle1"
      @selection-change="handleSelectionChange1"
      :header-cell-style="headerCellStyle1"
    >
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="序号" width="50" align="center">
        <template #default="{ $index }">
          <span>{{ $index + 1 }}</span>
        </template>
      </el-table-column>
      <el-table-column label="单件唯一码" width="100" align="center">
        <template #default="{ row, $index }">
          <div style="height: 25px; line-height: 25px">
            {{ row.uniqueCode }}
          </div>
        </template>
      </el-table-column>

      <el-table-column label="规格" width="100" align="center">
        <template #default="{ row, $index }">
          <div style="height: 25px; line-height: 25px">
            {{ row.specification }}
          </div>
        </template>
      </el-table-column>

      <el-table-column label="型号" width="100" align="center">
        <template #default="{ row, $index }">
          <div style="height: 25px; line-height: 25px">
            {{ row.model }}
          </div>
        </template>
      </el-table-column>

      <el-table-column label="材质" width="100" align="center">
        <template #default="{ row, $index }">
          <div style="height: 25px; line-height: 25px">
            {{ row.material }}
          </div>
        </template>
      </el-table-column>

      <!-- <el-table-column label="单件唯一码" width="100" align="center">
        <template #default="{ row, $index }">
          <el-input
            :readonly="true"
            v-model="row.uniqueCode"
            :style="{ height: '25px' }"
          />
        </template>
      </el-table-column>
      <el-table-column label="规格" width="100" align="center">
        <template #default="{ row, $index }">
          <el-input disabled v-model="row.specification" :style="{ height: '25px' }" />
        </template>
      </el-table-column>
      <el-table-column label="型号" width="100" align="center">
        <template #default="{ row, $index }">
          <el-input disabled v-model="row.model" :style="{ height: '25px' }" />
        </template>
      </el-table-column>
      <el-table-column label="材质" width="100" align="center">
        <template #default="{ row, $index }">
          <el-input disabled v-model="row.material" :style="{ height: '25px' }" />
        </template>
      </el-table-column> -->
      <el-table-column label="磨削量" width="100" align="center">
        <template #default="{ row, $index }">
          <el-input
            :disabled="isdisRepairApplication"
            v-model="row.grindingCapacity"
            :style="{ height: '25px' }"
              @blur="handleInput('grindingCapacity', $index)"
          />
        </template>
      </el-table-column>
      <el-table-column label="粗糙度" width="100" align="center">
        <template #default="{ row, $index }">
          <el-input
            :disabled="isdisRepairApplication"
            v-model="row.roughnessStandard"
            :style="{ height: '25px' }"
              @blur="roughnessStandard('roughnessStandard', $index)"
          />
        </template>
      </el-table-column>
      <el-table-column label="费用" width="100" align="center">
        <template #default="{ row, $index }">
          <el-input
            :disabled="isdisRepairApplication"
            v-model="row.expense"
            :style="{ height: '25px' }"
            @blur="handleInput('expense', $index)"
          />
        </template>
      </el-table-column>
      <el-table-column label="单件状态" width="100" align="center">
        <template #default="{ row, $index }">
          <el-select
            :disabled="isdisRepairApplication"
            v-model="row.singleStatus"
            :style="{ height: '25px' }"
            size="small"
          >
            <el-option label="完成" value="0" />
            <el-option label="报废" value="1" />
          </el-select>
        </template>
      </el-table-column>
      <el-table-column label="说明" width="auto" align="center">
        <template #default="{ row, $index }">
          <el-input v-model="row.comment" :style="{ height: '25px' }" />
        </template>
      </el-table-column>
    </el-table>
  </div>
  <el-container>
    <el-header height="65px" :style="{ 'border-bottom': '1px solid #ccc' }">
      <!-- 头部按钮 -->
      <el-row type="flex" justify="end" style="background-color: rgb(211, 227, 253)">
        <div>
          <el-button @click="searchButton" type="primary"> 查询</el-button>
          <el-button @click="handleAudit" type="success"> 审核</el-button>
          <el-button @click="deleteButton" type="danger"> 删除</el-button>
        </div>
        <!-- <div class="title">需求汇总统计表</div> -->
      </el-row>
      <div
        style="
          margin-left: 6rem;
          height: 30px;
          background: rgb(241, 244, 243);
          margin-bottom: 0;
          position: relative;
          display: flex;
          justify-content: flex-start;
        "
      >
        <el-input
          style="width: 10%; height: 25px; margin-left: 2px; margin-top: 2px"
          v-model="inputCode"
          placeholder="单据编号"
        >
          <template #prefix>
            <el-icon class="">
              <search />
            </el-icon>
          </template>
        </el-input>

        <!-- <el-input
          style="width: 10%; height: 25px; margin-left: 2px; margin-top: 2px"
          v-model="inputCode"
          placeholder="班组编号"
        >
          <template #prefix>
            <el-icon class="">
              <search />
            </el-icon>
          </template>
        </el-input> -->
      </div>
    </el-header>
    <el-container>
      <el-container>
        <el-main style="padding: 2px 2px 0 2px; margin-left: 6rem">
          <el-table
            v-loading="loading"
            ref="table"
            :data="tableData"
            border
            stripe
            :cell-style="cellStyle"
            :header-cell-style="headerCellStyle"
            @selection-change="handleSelectionChange"
            @row-dblclick="handleRowClick"
            @row-click="RowClick"
            :row-style="rowState"
            :row-key="(row: any) => row.id"
            :max-height="screenHeight"
            :height="screenHeight"
            :max-width="'300px'"
          >
            <el-table-column fixed type="index" width="80" align="center" />
            <el-table-column fixed type="selection" width="50" align="center" />

            <el-table-column prop="code" label="工单编号" width="120" align="center" />
            <el-table-column prop="name" label="班组名称" width="120" align="center" />
            <el-table-column
              prop="repairMode"
              label="返修方式"
              width="120"
              align="center"
            />
            <el-table-column
              prop="repairTime"
              label="返修周期"
              width="120"
              align="center"
            />
            <el-table-column
              prop="repairTimeUnit"
              label="单位"
              width="120"
              align="center"
            />
            <el-table-column
              prop="totalAmount"
              label="花费总金额"
              width="80"
              align="center"
            />
            <el-table-column prop="state" label="状态" width="120" align="center" />
            <el-table-column
              prop="returnTime"
              label="入库时间"
              width="120"
              align="center"
            />
            <el-table-column
              prop="djStatus"
              label="入库审核状态"
              width="120"
              align="center"
            />
            <el-table-column prop="creator" label="创建者" width="120" align="center" />
            <el-table-column
              prop="creationTime"
              label="创建时间"
              width="120"
              align="center"
            />
            <el-table-column prop="reviewer" label="审核者" width="120" align="center" />
            <el-table-column
              prop="reviewTime"
              label="审核时间"
              width="120"
              align="center"
            />
          </el-table>
        </el-main>
        <el-footer style="height: 20px">
          <div class="demo-pagination-block">
            <el-pagination
              v-model:current-page="page"
              v-model:page-size="limit"
              :page-sizes="[50, 500, 1000, 1500, 2000, 8000]"
              :small="true"
              :background="true"
              layout="total, sizes, prev, pager, next, jumper"
              :total="total"
              @size-change="handleSizeChange"
              @current-change="handleCurrentChange"
            />
          </div>
        </el-footer>
      </el-container>
    </el-container>
  </el-container>
  <SearchTableDialog
    ref="sed"
    @row-data="handleRowData"
    @row-datas="handleRowDatas"
  ></SearchTableDialog>
</template>
<script setup lang="ts">
import {
  ref,
  watch,
  reactive,
  onMounted,
  onBeforeMount,
  computed,
  nextTick,
  onUnmounted,
  toRefs,
} from "vue";
import { Delete, Edit, Search, Share, Upload, Calendar } from "@element-plus/icons-vue";
import {
  ElButton,
  ElDialog,
  dialogEmits,
  ElMessage,
  ElTable,
  TableColumnCtx,
  ElMessageBox,
} from "element-plus";
import type { FormInstance, FormRules } from "element-plus";

import { CircleCloseFilled } from "@element-plus/icons-vue";
import { useRouter } from "vue-router";
import axios from "../../axios/axiosInstance.ts";
import Cookies from "js-cookie";
import { format } from "date-fns";
import zhCn from "element-plus/dist/locale/zh-cn.mjs";
// crud封装组件
import * as crud from "../../components/utils/crud.ts";
import SearchTableDialog from "@/components/dialogs/SearchTableDialog.vue";
import * as notifications from "../../components/utils/notification.ts";
import Co from "../../components/utils/t-ui-plus-dev/packages/select-table/src/index.vue";

// 时间
// 获取当前时间
const getCurrentFormattedDateTime = () => {
  const currentDateTime = new Date();

  // 格式化当前时间
  const formattedDateTime = currentDateTime.toLocaleString("zh-CN", {
    year: "numeric",
    month: "2-digit",
    day: "2-digit",
    hour: "2-digit",
    minute: "2-digit",
    second: "2-digit",
  });
  // const formattedDateTime = format(currentDateTime, "YYYY-MM-dd HH:mm:ss");

  return formattedDateTime;
};
// 获取年月日
const getCurrentFormattedDate = () => {
  const currentDateTime = new Date();

  // 格式化当前时间，只获取年月日
  const formattedDate = currentDateTime.toLocaleString("zh-CN", {
    year: "numeric",
    month: "2-digit",
    day: "2-digit",
  });

  return formattedDate;
};
// 权限控制
const searchButtonPermissionsA = ref(false);
const menuId = ref(0);
const buttonVariables = {
  searchButtonPermissionsA,
};
const selectPermissionsButton = () => {
  const userName = Cookies.get("userName");
  axios({
    url: "/select/Permissions/Button",
    method: "post",
    data: {
      userName: userName,
      menuId: menuId.value,
    },
  }).then((res) => {
    res.data.forEach((button) => {
      const buttonName = button.buttonName;
      if (buttonVariables.hasOwnProperty(buttonName)) {
        buttonVariables[buttonName].value = true;
      }
    });
  });
};
selectPermissionsButton();
//权限结束
const tableData = ref([]);
const dialogTableVisible1 = ref(false);
const loading = ref(false);
const page = ref(1);
const limit = ref(50);
const total = ref(50);
const inputName = ref("");
const inputCode = ref("");
const selectBusinessDate = computed(() => ({
  page: page.value,
  limit: limit.value,
  inputCode: inputCode.value,
}));
const handleSizeChange = (val: number) => {
  selectBusinessType();
};
const handleCurrentChange = (val: number) => {
  selectBusinessType();
};
const searchButton = () => {
  selectBusinessType();
};
const selectBusinessType = async () => {
  loading.value = true;
  try {
    const res = await crud.fetchData(
      "/Rep/select/RepairOutsourcingAll",
      "post",
      selectBusinessDate.value
    );
    if (res.length == 0) {
      total.value = 0;
      tableData.value = [];
      loading.value = false;
      return;
    }
    console.log(res);
    res.forEach((item) => {
      item.state = item.state == 0 ? "未审核" : "已审核";
      item.djStatus = item.djStatus == 0 ? "未审核" : "已审核";
      item.repairMode = item.repairMode == 0 ? "自修" : "委外";
    });
    tableData.value = res;
    total.value = res[0].total;
    loading.value = false;
  } catch (error) {
    loading.value = false;
    console.error("请求失败:", error);
  }
};
selectBusinessType();
const handleRowClick = (row) => {
  isTotalAmount.value = true;
  dialogTableVisible1.value = true;
  showInsertButton.value = false;
  formMainTable.value.id = row.id;
  formMainTable.value.code = row.code;
  formMainTable.value.name = row.name;
  formMainTable.value.repairMode = row.repairMode;
  formMainTable.value.supplier = row.supplier;
  formMainTable.value.supplierAddress = row.supplierAddress;
  formMainTable.value.creator = row.creator;
  formMainTable.value.creationTime = row.creationTime;
  formMainTable.value.repairTime = row.repairTime;
  formMainTable.value.djStatus = row.djStatus;
  formMainTable.value.repairTimeUnit = row.repairTimeUnit;
  const userName = Cookies.get("userName");
  const currentFormattedDateTime = getCurrentFormattedDateTime();
  const currentFormattedDate = getCurrentFormattedDate();
  form.xgsj = currentFormattedDateTime;
  form.xgr = userName;
  // 回显测算类型
  // 回显子表
  axios({
    url: "/Rep/select/RepairApplicationSub",
    method: "post",
    data: {
      id: row.id,
    },
  }).then((res) => {
    const testList = res.data;
    console.log(testList);

    if (testList.length === 0) {
      for (let a = 0; a < 21; a++) {
        addRow();
      }
    } else {
      const formattedData = testList.map((test, index) => ({
        autoId: test.autoId,
        id: test.id,
        mid: test.mid,
        componentId: test.componentId,
        equipmentStructureId: test.equipmentStructureId,
        material: test.material,
        specification: test.specification,
        model: test.model,
        uniqueCode: test.uniqueCode,
        grindingCapacity: test.grindingCapacity,
        roughnessStandard: test.roughnessStandard,
        expense: test.expense,
        singleStatus: test.singleStatus,
      }));
      tableData1.value = formattedData;
    }
    console.log(tableData1.value);
  });
};
const calculateTotalAmount = () => {
  let total = 0;
  for (let i = 0; i < tableData1.value.length; i++) {
    // 确保转换为数值类型进行累加，同时处理非数字或空值的情况
    const expense = parseFloat(tableData1.value[i].expense) || 0;
    total += expense;
  }
  // 将计算出的总和赋值给主表单的totalAmount
  formMainTable.value.totalAmount = total;
};
const handleInput = (prop, index) => {
  const val = tableData1.value[index][prop];
  if (!isNaN(parseFloat(val)) && isFinite(val)) {
    // 将数字保留四位小数
    tableData1.value[index][prop] = parseFloat(val).toFixed(4);
  } else {
    // 如果不是有效数字，清空表单
    tableData1.value[index].totalAmount = "";
  }
  calculateTotalAmount();
};
// 表格
const headerCellStyle = {
  // E9E9E7
  borderColor: "#B9C9C7",
  backgroundColor: "#F2F4FA", // 表头背景颜色
  fontWeight: "bold", // 表头文字粗细
  color: "#1F2129",
  // padding: "0 0 0 30px",
};
const rowState = (arg) => {
  return {
    height: "20px", // 设置合适的行高值
    fontSize: "12px", // 设置合适的字体大小值
    // color: "black",
  };
};
const RowClick = (row, selection) => {
  table.value.toggleRowSelection(row);
};
const selectedRows = ref([]);
const table = ref();

const cellStyle = ({ row, column, rowIndex, columnIndex }) => {
  if (selectedRows.value.find((selectedRow) => selectedRow.id === row.id)) {
    return {
      backgroundColor: "#DFF0DB !important",
      borderColor: "#B9C9C7",
      padding: "4px",
    };
  } else {
    return { borderColor: "#B9C9C7", padding: "4px", margin: 0 };
  }
};
const handleSelectionChange = (selection: any) => {
  selectedRows.value = selection;
};
const screenHeight = ref(null);
const screenWidth = ref(null);
const childTableHeight = ref(null);

const getScreenHeight = () => {
  childTableHeight.value = `${window.innerHeight}` - 203;
  screenHeight.value = window.innerHeight - 146;
  screenWidth.value = window.innerWidth;
};
getScreenHeight();
const requestDataAsid = computed(() => ({
  deleteIdList: selectedRows.value,
}));

const deleteButton = async () => {
  try {
    const result = await notifications.showConfirmDialog("", "请确认删除", "success");
    if (result) {
      if (selectedRows.value.length === 0) {
        notifications.showMessage("请至少选择一行进行操作", "error");
        return;
      }

      const res = await crud.sendRequest(
        "/Bdy/delete/BusinessDepartmentType/Mapping",
        "post",
        requestDataAsid.value
      );
      selectBusinessType();
    }
  } catch (error) {
    console.error("请求失败:", error);
  }
};
const handleAudit = () => {
  if (selectedRows.value.length === 0) {
    alert("请勾选需要审核的数据！");
    return;
  }
  if (selectedRows.value[0].djStatus === "已审核") {
    alert("已经审核的数据无法再次审核！");
    return;
  }
  if (confirm("确认审核吗？") == false) {
    return;
  }
  // .then(() => {
  const userName = Cookies.get("userName");
  axios({
    url: "/Rep/audit/RepairOutsourcing",
    method: "post",
    data: {
      userName: userName,
      id: selectedRows.value.map((row) => row.id),
    },
  }).then((res) => {
    if (res.data.data == 200) {
      alert("审核成功！");
      // selectpurposes();
      searchButton();
      return;
    }
    ElMessage({
      showClose: true,
      message: "审核失败！",
      type: "error",
    });
  });

  // .catch(() => {});
};
const asideListData = ref([]);
const asideList = async () => {
  try {
    const res = await crud.fetchData(
      "/BusinessType/select/BusinessType/All/Auto1",
      "post",
      requestData.value
    );
    asideListData.value = res; // 将结果赋值给 ref
  } catch (error) {
    console.error("请求失败:", error);
  }
};
const getParentIds = (nodeId) => {
  const parentIds = [];
  let currentNode = asideListData.value.find((node) => node.id === nodeId);
  while (currentNode && currentNode.parentID !== null) {
    parentIds.push(currentNode.id);
    currentNode = asideListData.value.find((node) => node.id === currentNode.parentID);
  }
  return parentIds.reverse();
};

// 新增页面展示
const openInseart = () => {
  isTotalAmount.value = false;
  dialogTableVisible1.value = true;
  showInsertButton.value = true;
  nextTick(() => {
    selectBusinessTypeAside();
    for (let a = 0; a < 21; a++) {
      addRow();
    }
  });
};

interface RuleForm {
  id: string;
  workOrderCode: string;
  grindingProcessStandard: string;
  supplier: string;
  status: true;
  supplierAddress: string;
}
const form = reactive<RuleForm>({
  id: "",
  workOrderCode: "",
  grindingProcessStandard: "",
  supplier: "",
  supplierAddress: "",
});
const ruleFormRef = ref<FormInstance>();
const rules = reactive<FormRules<RuleForm>>({
  // name: [{ message: "请输入班组名称", trigger: "blur"  }],
});
// 子表展示
const cellStyle1 = ({ row, column, rowIndex, columnIndex }) => {
  return { borderColor: "#B9C9C7", padding: "0px", margin: 0 };
};
const showInsertButton = ref(true);
const multipleTableRef = ref();
const handleSelectionChange1 = (val: any[]) => {
  console.log("Selected Rows:", val);
};

const defaultRowData = {
  id: "",
  componentId: "", //零件id
  equipmentStructureId: "",
  expense: "", //费用
  uniqueCode: "", //设备编码
  material: "", //材质
  specification: "", //规格
  model: "", //型号
  grindingCapacity: "", //磨削量
  roughnessStandard: "", //粗糙度
  comment: "", //说明
  singleStatus: "0", //单件状态
};

const tableData1 = ref([
  {
    ...defaultRowData,
  },
  // More data...
]);
const OFFdialogTableVisible = () => {
  dialogTableVisible1.value = false;
  selectBusinessType();
  flushed();
  clearForm();
};
const clearForm = () => {
  Object.keys(form).forEach((key) => {
    if (typeof form[key] === "boolean") {
      Vue.set(form, key, true);
    } else {
      Vue.set(form, key, "");
    }
  });
};

const flushed = () => {
  organizationSelect.value = "";
  parentIDValue.value = "";
  isDisabled.value = true;
  Object.keys(form).forEach((key) => {
    form[key] = "";
  });
  tableData1.value = [];
  for (let a = 0; a < 21; a++) {
    addRow();
  }
};
const addRow = () => {
  tableData1.value.push({ ...defaultRowData });
};
const requestFormTable = computed(() => {
  const usefulDataArray = tableData1.value.filter((item) => item.uniqueCode !== "");
  const userName = Cookies.get("userName");
  return {
    childList: usefulDataArray,
    id: formMainTable.value.id,
    supplier: formMainTable.value.supplier,
    supplierAddress: formMainTable.value.supplierAddress,
    repairTime: formMainTable.value.repairTime,
    repairTimeUnit: formMainTable.value.repairTimeUnit,
    applicant: formMainTable.value.creator,
    applicationTime: formMainTable.value.creationTime,
    totalAmount: formMainTable.value.totalAmount,
    repairMode: formMainTable.value.repairMode == "委外" ? 1 : 0,
    userName: userName,
  };
});

const getAllData = async () => {
  try {
    if (formMainTable.value.djStatus === "已审核") {
      alert("已经审核的数据无法再次保存！");
      return;
    }
    const result = await notifications.showConfirmDialog("", "请确认保存", "success");
    console.log(requestFormTable.value);
    if (!result) {
      // 用户点击了取消按钮，不执行保存操作
      return;
    }
    const res = await crud.sendRequest(
      "/Rep/insert/RepairOutsourcing",
      "post",
      requestFormTable.value
    );

    if (res.code == 200) {
      OFFdialogTableVisible();
    }
  } catch (error) {
    console.error("请求失败:", error);
  }
};

const getSelectedData = () => {
  const selectedRows = multipleTableRef.value.getSelectionRows();
};

const deleteSelectedRows = () => {
  const selectedRows = multipleTableRef.value.getSelectionRows();
  selectedRows.forEach((row) => {
    const index = tableData1.value.indexOf(row);
    if (index !== -1) {
      tableData1.value.splice(index, 1);
    }
  });
};

const deleteRow = (row: any) => {
  const index = tableData1.value.indexOf(row);
  if (index !== -1) {
    tableData1.value.splice(index, 1);
  }
};
const headerCellStyle1 = {
  borderColor: "#B9C9C7",
  backgroundColor: "#F2F4FA",
  fontWeight: "bold",
  color: "#1F2129",
  height: "40px",
  margin: 0,
  padding: 0,
};
// 弹窗
const indexEmployeeJob = ref(0);
const isRepairApplication = ref(false);
const isdisRepairApplication = ref(false);
const isTotalAmount = ref(true);
const handleValueRangeChange = async (value) => {
  tableData1.value = [];
  for (let a = 0; a < 21; a++) {
    addRow();
  }
  let repairMode = formMainTable.value.repairMode;
  if (repairMode == "0") {
    isRepairApplication.value = false;
    isdisRepairApplication.value = false;
  } else {
    isRepairApplication.value = true;
    isdisRepairApplication.value = true;
  }
};
const openWorkOrderCode = async () => {
  sed.value.dialogTableVisible = true;
  await openDial();
};
const sed = ref<any>(null);
const tableDemo = ref([
  { type: "index", fixed: true, width: "60", align: "center" },
  //   { type: "selection", width: "65", align: "center" },
  //   { prop: "teamID", label: "ID", width: "120", align: "center" },
  { prop: "code", label: "班组编号", width: "120", align: "center" },
  { prop: "teamName", label: "班组名称", width: "150", align: "center" },
  { prop: "description", label: "说明", width: "150", align: "center" },
]);

const openDial = () => {
  sed.value.ifRowChoose = false;
  sed.value.ifdynamic1 = true;
  sed.value.dynamicPlaceholder1 = "班组名称";
  sed.value.ifdynamic2 = true;
  sed.value.dynamicPlaceholder2 = "班组编号";
  sed.value.ifdynamic3 = false;
  sed.value.tableColumns = tableDemo.value;
  sed.value.apiUrl = "/Team/select/Team/Auto1/tc";
  sed.value.searchInput();
};
// const flushed1 = () => {
//   tableData1.value = [];
//   for (let a = 0; a < 21; a++) {
//     addRow();
//   }
// };

const handleRowData = async (row) => {
  console.log(row);
  formMainTable.value.name = row.teamName;
  formMainTable.value.workTeam = row.teamID;
};

const handleRowDatas = (row) => {};
// 业务分类下拉
const parentIDValue = ref("");
const parentIDOptions = ref([]);
const transformResToOption = (data) => {
  const transform = (items) => {
    return items.map((item) => ({
      value: item.id,
      label: item.name,
      level: item.level,
      children: item.children ? transform(item.children) : [],
    }));
  };

  return transform(data);
};
const props = {
  checkStrictly: true,
};
const requestData = computed(() => ({}));
const selectBusinessTypeAside = async () => {
  try {
    const res = await crud.fetchData(
      "/BusinessType/select/BusinessType/Aside/Auto1",
      "post",
      requestData.value
    );

    const transformedRes = transformResToOption(res);
    parentIDOptions.value = transformedRes;
  } catch (error) {
    console.error("请求失败:", error);
  }
};
const findLevelByValue = (options, targetValue) => {
  for (const option of options) {
    // 如果当前选项的值与目标值匹配，则返回该选项的级别
    if (option.value === targetValue) {
      return option.label;
    }
    // 如果当前选项有子选项，则递归调用该函数
    if (option.children && option.children.length > 0) {
      const label = findLevelByValue(option.children, targetValue);
      // 如果在子选项中找到了目标值，则返回找到的级别
      if (label !== undefined) {
        return label;
      }
    }
  }
  // 如果未找到目标值，则返回 undefined
  return undefined;
};
// const handleChange = (value) => {
//   const selectedValue = value[value.length - 1];
//   form.businessTypeID = selectedValue;
//   const label = findLevelByValue(parentIDOptions.value, selectedValue);
//   form.businessTypeName = label;
// };

// 查询下拉框;
// 组织类型
const options = reactive([
  {
    value: "Option1",
    label: "Option1",
  },
]);

const transformResToOptions = (res) => {
  return res.map((item) => {
    return {
      value: item.code,
      label: item.codeName,
    };
  });
};

const selectSystem_parameter_sub_tableDate = reactive({
  tableName: "BusinessDepartmentTypeMappingTable",
  field: "organizationType",
});
const organizationSelect = ref("");

const selectSystem_parameter_sub_table = async () => {
  try {
    const res = await crud.fetchData(
      "/BusinessType/select/System_parameter_sub_table",
      "post",
      selectSystem_parameter_sub_tableDate
    );
    options.splice(0, options.length, ...transformResToOptions(res));
  } catch (error) {
    console.error("请求失败:", error);
  }
};
selectSystem_parameter_sub_table();
const isDisabled = ref(true);
const clickOrganizationSelect = () => {
  form.organizationType = organizationSelect.value;
  form.departmentID = "";
  form.name = "";
  isDisabled.value = false;
};

// 定义前端数据模型
const formMainTable = ref({
  totalAmount: "", //花费总金额
  id: "",
  djStatus: "",
  code: "", // 工单编号
  workTeam: "", // 班组
  name: "", // 班组名称
  repairMode: "0", // 返修方式
  repairTime: "", // 周期
  repairTimeUnit: "小时", // 单位
  supplier: "", // 供应商
  supplierAddress: "", // 地址
  returnTime: "", // 入库时间
  equipmentName: "", // 设备名称
  uniqueCode: "", // 单件编码
  state: "", // 状态
  explain: "", // 说明
  creator: "", // 创建者
  creatorID: "", // 创建者ID
  creationTime: "", // 创建时间
  reviewer: "", // 审核者
  reviewerID: "", // 审核者ID
  reviewTime: "", // 审核时间
  modifier: "", // 修改者
  modifierID: "", // 修改者ID
  modificationTime: "", // 修改时间
});

const dynamicTitle = ref("展开参数");

const handleChange = (val: string[]) => {
  if (dynamicTitle.value == "折叠参数") {
    dynamicTitle.value = "展开参数";
    //  scollbarHeight.value = 724;
    childTableHeight.value = `${window.innerHeight}` - 252;
    collapsed.value = 48;
    return;
  }
  dynamicTitle.value = "折叠参数";
  //   affixOffset.value = 500;
  //   scollbarHeight.value = 472;
  childTableHeight.value = `${window.innerHeight}` - 513;
  collapsed.value = 300;
  return;
};
//下拉表格
const selectTable = ref();
const stateTable: any = reactive({
  table: {
    total: 0,
    currentPage: 1,
    data: [],
    columns: [
      { prop: "uniqueCode", label: "单件唯一码", width: "150", align: "center" },
      { prop: "equipmentName", label: "设备名称", width: "150", align: "center" },
      {
        prop: "materialCode",
        label: "物料编码",
        width: "150",
        align: "center",
      },
      { prop: "material", label: "材质", width: "150", align: "center" },
      { prop: "specification", label: "规格", width: "150", align: "center" },
      { prop: "model", label: "型号", width: "150", align: "center" },
    ],
  },
});
onMounted(() => {
  getData(1);
});

const uniqueCode = ref("");
const getData = async (pageNum) => {
  const res = await crud.fetchData("/Rep/select/OutsourcingResultList", "post", {
    page: pageNum,
    limit: 1000,
    input2: uniqueCode.value,
  });
  console.log(res);
  if (res.length == 0) {
    stateTable.table.total = 0;
    return;
  }
  stateTable.table.data = res;
  stateTable.table.total = res[0].total;
};
// 获取当前的页码
const pageChange = (val) => {
  console.log("获取当前的页码", val);
  stateTable.table.currentPage = val;
  getData(val);
};
const handleStatusChange = (row) => {
  let text = row.enableStatus === 1 ? "启用" : "废止";
  ElMessageBox.confirm(`确认要${text}这条数据吗？`, "警告", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(() => {
      console.log("点击确定");
    })
    .catch(() => {
      console.log("点击取消");
    });
};
const radioChange = async (row) => {
  addRow();
  for (let i = 0; i < tableData1.value.length; i++) {
    if (
      tableData1.value[i].uniqueCode == "" ||
      tableData1.value[i].uniqueCode == undefined
    ) {
      tableData1.value[i].componentId = row.componentId;
      tableData1.value[i].equipmentStructureId = row.equipmentStructureId;
      tableData1.value[i].material = row.material;
      tableData1.value[i].specification = row.specification;
      tableData1.value[i].model = row.model;
      tableData1.value[i].uniqueCode = row.uniqueCode;

      return;
    } else if (tableData1.value[i].uniqueCode === row.uniqueCode) {
      // Show a warning or handle the duplicate here
      notifications.showMessage("第" + (i + 1) + "单件唯一码重复", "error");
      return;
    }
  }

  selectTable.value.clear();
};
const filterMethod = async (val) => {
  uniqueCode.value = val;
  getData(stateTable.table.currentPage);
};
const handleBlurTable = () => {
  selectTable.value.clear();
};
const rowState1 = (arg) => {
  return {
    height: "20px", // 设置合适的行高值
    fontSize: "12px", // 设置合适的字体大小值
  };
};
</script>
<style scoped>
.el-table {
  /* --el-table-row-hover-bg-color: rgba(0, 158, 250, 0.219) !important; */
  /* --el-table-row-hover-bg-color: #fef5f0 !important; */
  --el-table-row-hover-bg-color: rgba(254, 245, 240, 0.8) !important;
}

/* 选中 */
.el-table {
  /* --el-table-row-hover-bg-color: #fef5f0 !important; */
  --el-table-row-hover-bg-color: rgba(254, 245, 240, 0.8) !important;
}

.down-tree ::v-deep .el-tree-node.is-expanded > .el-tree-node__children {
  display: inline;
}

.down-tree {
  height: 100%;
}

.demo-pagination-block {
  float: right;
}

.custom-dialog {
  position: fixed;
  top: 10em;
  left: 50%;
  width: 20%;
  /* 其他样式... */
}

.demo-form-inline .el-input {
  --el-input-width: 220px;
}

.labs {
  margin-bottom: 0px;
}

.lab {
  background-color: rgba(247, 247, 247, 0.903);
  /* border-radius: 5px; */
  text-align: center;
  margin-bottom: 0px;
  text-align: right;
}
</style>
